import system
import server
import os
import time

def sys_power_on():
    """
    
    """
    first_centural_ac = system.CenturalAC()
    first_server = server.Server(port=8000)
    first_server.run()
    print('tcp server started')
    first_scheduler = system.Scheduler(maxitem=3, maxtime=5, service_interval=3)
    first_database = system.DataBase()
    # 利用名为.isopen的文件判断进程是否开启
    #if os.path.exists(r'.is_open'):
    #    raise Exception('System thread already exist!')
    is_open = open('.is_open', 'w')
    is_open.write(str(os.getpid()))
    is_open.close()

if __name__ == "__main__":
    '''
        管理员部分
    '''
    sys_power_on()
    new_ac = system.CenturalAC()
    roomList = [200 + i for i in range(10)]
    new_ac.set_para(True, 22., 1, 16, 25,
        0.5, 1, 1.5, roomList)
    new_ac.startup()
    '''
        前台部分
    '''
    new_recption = system.ReceptionFacade([])
    new_user = system.UserFacade(0, 0, [])
    rid = new_recption.checkin()
    new_user.change_room_temp(rid, 30)
    new_user.power_on(rid)
    rid = new_recption.checkin()
    new_user.power_on(rid)
    new_user.change_room_temp(rid, 30)
    rid = new_recption.checkin()
    new_user.power_on(rid)
    new_user.change_room_temp(rid, 30)
    rid = new_recption.checkin()
    new_user.power_on(rid)
    new_user.change_room_temp(rid, 30)
    new_user.change_fan_speed(rid, 1)
    new_user.change_fan_speed(rid, 1)
    new_user.change_fan_speed(rid, 1)
    new_user.change_fan_speed(rid, 1)
    if rid == -1:
        raise Exception('No vacant room')
    '''
        用户部分
    '''
    thesch = system.Scheduler()
    thesch.show_queue()
    print('trying to change temp:', new_user.change_target_temp(rid, 100))
    time.sleep(2)
    print(new_user.change_target_temp(rid, 20))
    time.sleep(3)
    print(new_ac.get_room_temp(rid), new_ac.get_mode(rid))
    time.sleep(10)
    #new_user.change_room_temp(rid, 22.5)
    time.sleep(5)
    print(new_ac.get_room_temp(rid), new_ac.get_mode(rid))
    thesch.show_queue()
    time.sleep(48)
    new_user.power_off(rid)
    '''
        前台部分
    '''
    time.sleep(6)
    print(new_recption.get_bill(rid))
    new_recption.checkout(200)
    new_recption.checkout(201)
    new_recption.checkout(202)
    new_recption.checkout(203)
    '''
        管理员部分
    '''
    the_ac = system.CenturalAC()
    db = system.DataBase()
    rl = db.query_details()
    for r in rl:
        r.show()
    the_ac.shutdown()
